package com.lzj.demo.design.strategy;

import com.lzj.demo.design.common.ServerResult;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件解析工厂
 * @author Faker
 * @date 2022-11-1
 * */
@Component
public class FileResolveFactory implements ApplicationContextAware {

    private Map<FileTypeResolveEnum, IFileStrategy> iFileStrategyMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IFileStrategy> map = applicationContext.getBeansOfType(IFileStrategy.class);
        map.values().forEach(strategyService -> iFileStrategyMap.put(strategyService.gainFileType(), strategyService));
    }

    public ServerResult resolveFile(FileTypeResolveEnum fileTypeResolveEnum, Object param) {
        IFileStrategy iFileStrategy = iFileStrategyMap.get(fileTypeResolveEnum);
        iFileStrategy = Objects.nonNull(iFileStrategy) ? iFileStrategy:iFileStrategyMap.get(FileTypeResolveEnum.File_DEFAULT_RESOLVE);
        return iFileStrategy.resolve(param);
    }
}
